package hu.lacimol.tutorial.todo.scheduling;

import hu.lacimol.tutorial.todo.service.TodoService;

import java.util.Date;
import java.util.HashMap;

import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.atlassian.sal.api.lifecycle.LifecycleAware;
import com.atlassian.sal.api.scheduling.PluginScheduler;

public class TodoMonitorImpl implements TodoMonitor, LifecycleAware {
	
	private final static Logger logger = LoggerFactory.getLogger(TodoMonitorImpl.class);
	private static final String JOB_NAME = TodoMonitorImpl.class.getName() + ":job";
	private static final long INTERVAL = DateTimeConstants.MILLIS_PER_MINUTE;
	
	private final PluginScheduler pluginScheduler;
	private TodoService todoService;
	private Date lastRun;
	
	private HashMap<String, Object> jobDataMap = new HashMap<String, Object>();
	
	public TodoMonitorImpl(PluginScheduler pluginScheduler, TodoService todoService) {
		this.pluginScheduler = pluginScheduler;
		this.todoService = todoService;
	}
	
	@Override
	public void schedule() {
		
		jobDataMap.put("TodoMonitorImpl:instance", TodoMonitorImpl.this);
		jobDataMap.put("TodoService", todoService);
		
		Date startTime = DateTime.now().toDate();
		pluginScheduler.scheduleJob(JOB_NAME, TodoTask.class, jobDataMap, startTime, INTERVAL);
		
		logger.info(String.format("TodoMonitorImpl scheduled to run every %d ms", INTERVAL));
		
	}
	
	@Override
	public void onStart() {
		schedule();
	}
	
	@Override
	public void setLastRun(Date lastRun) {
		this.lastRun = lastRun;
	}
	
	@Override
	public Date getLastRun() {
		return lastRun;
	}
	
}
